package com.example.myapplication

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*

/**
 * 优化版患者适配器 - 使用DiffUtil提升性能
 */
class OptimizedPatientAdapter(
    private val onItemClick: (Patient) -> Unit,
    private val onDeleteClick: (Patient) -> Unit,
    private val onEditClick: (Patient) -> Unit
) : RecyclerView.Adapter<OptimizedPatientAdapter.PatientViewHolder>() {

    private var patients: List<Patient> = emptyList()
    
    // 复用DateFormat对象，避免重复创建
    private val dateFormat by lazy { SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) }
    private val timeFormat by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) }

    /**
     * ViewHolder
     */
    class PatientViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textName: TextView = itemView.findViewById(R.id.textName)
        val textExaminationDate: TextView = itemView.findViewById(R.id.textExaminationDate)
        val textReporter: TextView = itemView.findViewById(R.id.textReporter)
        val textExaminationName: TextView = itemView.findViewById(R.id.textExaminationName)
        val textDepartment: TextView = itemView.findViewById(R.id.textDepartment)
        val textReportTime: TextView = itemView.findViewById(R.id.textReportTime)
        val textUserType: TextView = itemView.findViewById(R.id.textUserType)
        val buttonDelete: Button = itemView.findViewById(R.id.buttonDelete)
        val buttonEdit: Button = itemView.findViewById(R.id.buttonEdit)
        
        // 缓存用户类型文本，避免重复计算
        private val userTypeCache = mutableMapOf<UserType, String>()
        
        fun bind(
            patient: Patient, 
            dateFormat: SimpleDateFormat, 
            timeFormat: SimpleDateFormat,
            onItemClick: (Patient) -> Unit,
            onDeleteClick: (Patient) -> Unit,
            onEditClick: (Patient) -> Unit
        ) {
            // 设置基本信息
            textName.text = "患者: ${patient.name}"
            textExaminationDate.text = "检查日期: ${dateFormat.format(patient.examinationDate)}"
            textReporter.text = "汇报人: ${patient.reporter}"
            textExaminationName.text = "检查项目: ${patient.examinationName}"
            textDepartment.text = "科室: ${patient.department}"
            textReportTime.text = "上报时间: ${timeFormat.format(patient.reportTime)}"
            
            // 使用缓存的用户类型文本
            val userTypeText = userTypeCache.getOrPut(patient.reportedByType) {
                when (patient.reportedByType) {
                    UserType.SUPER_SUPER_ADMIN -> "大总管理员"
                    UserType.SUPER_ADMIN -> "总管理员"
                    UserType.DEPARTMENT_ADMIN -> "科室管理员"
                    UserType.USER -> "普通用户"
                    else -> "未知角色"
                }
            }
            textUserType.text = "上报用户类型: $userTypeText"
            
            // 设置点击事件
            itemView.setOnClickListener { onItemClick(patient) }
            buttonDelete.setOnClickListener { onDeleteClick(patient) }
            buttonEdit.setOnClickListener { onEditClick(patient) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PatientViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_patient, parent, false)
        return PatientViewHolder(view)
    }

    override fun onBindViewHolder(holder: PatientViewHolder, position: Int) {
        holder.bind(
            patients[position], 
            dateFormat, 
            timeFormat,
            onItemClick,
            onDeleteClick,
            onEditClick
        )
    }

    override fun getItemCount(): Int = patients.size

    /**
     * 使用DiffUtil优化列表更新性能
     */
    fun updatePatients(newPatients: List<Patient>) {
        val diffCallback = PatientDiffCallback(patients, newPatients)
        val diffResult = DiffUtil.calculateDiff(diffCallback)
        
        patients = newPatients
        diffResult.dispatchUpdatesTo(this)
    }
    
    /**
     * 获取指定位置的患者
     */
    fun getPatientAt(position: Int): Patient? {
        return if (position in 0 until patients.size) {
            patients[position]
        } else {
            null
        }
    }
    
    /**
     * 清空数据，释放内存
     */
    fun clear() {
        val oldSize = patients.size
        patients = emptyList()
        notifyItemRangeRemoved(0, oldSize)
    }

    /**
     * DiffUtil回调 - 用于高效更新列表
     */
    private class PatientDiffCallback(
        private val oldList: List<Patient>,
        private val newList: List<Patient>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int = oldList.size

        override fun getNewListSize(): Int = newList.size

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition].id == newList[newItemPosition].id
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            val oldPatient = oldList[oldItemPosition]
            val newPatient = newList[newItemPosition]
            
            return oldPatient.name == newPatient.name &&
                    oldPatient.examinationDate == newPatient.examinationDate &&
                    oldPatient.reporter == newPatient.reporter &&
                    oldPatient.examinationName == newPatient.examinationName &&
                    oldPatient.department == newPatient.department &&
                    oldPatient.reportTime == newPatient.reportTime &&
                    oldPatient.reportedByType == newPatient.reportedByType
        }
    }
}